package com.example.demo.config.builder;

import java.util.EnumSet;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;

import com.example.demo.config.enum_.OrderEvents;
import com.example.demo.config.enum_.OrderStates;

import lombok.extern.slf4j.Slf4j;

/**
 * 构建订单状态机
 * @author hello
 *
 */
@Component
@Slf4j
public class OrderStateMachineBuilder {
	@Autowired
	private BeanFactory beanFactory;
	
	public static final String MACHINEID="orderMachine"; 
	public StateMachine<OrderStates, OrderEvents> build() throws Exception {
		StateMachineBuilder.Builder<OrderStates, OrderEvents>  builder = StateMachineBuilder.builder();
		log.info("构建订单状态机");
		builder.configureConfiguration().withConfiguration().machineId(MACHINEID).beanFactory(beanFactory);
		
		builder.configureStates().withStates().initial(OrderStates.UNPAID).states(EnumSet.allOf(OrderStates.class));
		
		builder.configureTransitions()
			.withExternal()
			.source(OrderStates.UNPAID)
			.target(OrderStates.WAITING_FOR_RECEIVE)
			.event(OrderEvents.PAY)
			.action(action())
			.and()
		.withExternal()
			.source(OrderStates.WAITING_FOR_RECEIVE).target(OrderStates.DONE)
			.event(OrderEvents.RECEIVE);
		return builder.build();
	}
	
	@Bean
    public Action<OrderStates, OrderEvents> action() {
        return new Action<OrderStates, OrderEvents>() {
            @Override
            public void execute(StateContext<OrderStates, OrderEvents> context) {
               System.out.println(context);
            }
        };
    }
}
